﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Configuration;
using System.Net.Http;
using System.Text;
using FgoDataCrawler.Crawler;
using FgoDataCrawler.Entity;
using Newtonsoft.Json;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace FgoDataCrawler
{
    class Program
    {
        static void Main(string[] args)
        {
            // WikiaCrawler wikiaCrawler = new WikiaCrawler();
            // AppMediaCrawler appmediaCrawler = new AppMediaCrawler();
            // FgowikiCrawler fgowikiCrawler = new FgowikiCrawler();

            // var wikiaServants = wikiaCrawler.CrawlServantList();
            // StringBuilder sb = new StringBuilder();
            // foreach (var wikiaServant in wikiaServants)
            // {
            //     sb.AppendLine(string.Format("{0},{1},{2}", wikiaServant.Id, wikiaServant.JapaneseName, wikiaServant.EnglishName));
            //     // Console.WriteLine("{0}\t{1}", wikiaServant.Id, wikiaServant.MainAvatar);
            // }
            // File.WriteAllText(@"D:\temp\servant_names.csv", sb.ToString());

            // var appmediaServants = appmediaCrawler.FetchServents();

            // int success = 0;
            // foreach (var w in wikiaServants)
            // {
            //     // if (string.IsNullOrEmpty(servant.JapaneseName)) continue;
            //     // Console.WriteLine("No.{0:000}\t{1}", servant.Id, servant.JapaneseName);
            //     foreach (var am in appmediaServants)
            //     {
            //         // Console.WriteLine("{0}\t{1}", servant.AppMediaId, servant.JapaneseName);
            //         if (w.JapaneseName == am.JapaneseName)
            //         {
            //             w.AppMediaId = am.AppMediaId;
            //             success++;
            //             break;
            //         }
            //     }
            //     if (w.JapaneseName!=null && w.AppMediaId == null)
            //     {
            //         Console.WriteLine("未找到与No.{0:000} {1}对应的数据", w.Id, w.JapaneseName);
            //     }
            // }
            // Console.WriteLine("成功匹配数据{0}条", success);

            // ExportServantTable(wikiaServants, appmediaServants);

            // var appmediaSSR = appmediaCrawler.FetchLeaderBoard(5);
            // var ngaSSR = LeaderBoardGenerator.Generate(appmediaSSR);
            // File.WriteAllText(@"D:\temp\leaderboard_ssr.json", JsonConvert.SerializeObject(ngaSSR));
            // 
            // var appmediaSR = appmediaCrawler.FetchLeaderBoard(4);
            // var ngaSR = LeaderBoardGenerator.Generate(appmediaSR);
            // File.WriteAllText(@"D:\temp\leaderboard_sr.json", JsonConvert.SerializeObject(ngaSR));

            // ExportServantNames(fgowikiCrawler.FetchServants());

            FgowikiDataExporter exporter = new FgowikiDataExporter();
            exporter.LoadErrata(@"App_Data\errata.xlsx");
            exporter.ExportAll(@"D:\temp\fgowiki_data.xlsx");

            Console.WriteLine("按任意键结束 ...");
            Console.ReadKey();
        }

        static void ExportServantTable(IList<ServantInfo> wikiaServants, IList<ServantInfo> appmediaServants)
        {
            var wikiaServantsGroupByClass = (from s in wikiaServants group s by s.Class);
            var appmediaServantsGroupByClass = (from s in appmediaServants group s by s.Class);

            Dictionary<string, List<ServantInfo>> wikiaServantsDict = new Dictionary<string, List<ServantInfo>>();
            Dictionary<string, List<ServantInfo>> appmediaServantsDict = new Dictionary<string, List<ServantInfo>>();

            foreach (var g in wikiaServantsGroupByClass)
            {
                wikiaServantsDict[g.Key] = g.ToList();
            }
            foreach (var g in appmediaServantsGroupByClass)
            {
                appmediaServantsDict[g.Key] = g.ToList();
            }

            GenerateDocument(wikiaServantsDict, appmediaServantsDict);
        }

        static void GenerateDocument(Dictionary<string, List<ServantInfo>> wikiaServantsDict, Dictionary<string, List<ServantInfo>> appmediaServantsDict)
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("sheet1");
            string[] classNames = new string[]
            {
                "Saber",
                "Archer",
                "Lancer", 
                "Rider",
                "Caster",
                "Assassin",
                "Berserker",
                "Extra"
            };

            int rowNo = 1;
            foreach (var className in classNames)
            {
                IRow firstRow = sheet.CreateRow(rowNo++);
                firstRow.CreateCell(0).SetCellValue(className);

                int startAt = rowNo;
                List<ServantInfo> wikia = wikiaServantsDict[className];
                List<ServantInfo> appmedia = appmediaServantsDict[className];
                Dictionary<string, int> nameCache = new Dictionary<string, int>();

                bool mash = false;
                int wikiaCounter = 0;
                foreach (var s in wikia)
                {
                    // 几个例外：
                    // No.001 玛修只输出其中一个
                    if (s.Id == 1)
                    {
                        if (!mash) mash = true;
                        else continue;
                    }
                    // No.081 Berserker 海德 不输出
                    if (s.Id == 81 && s.Class == "Berserker") continue;
                    // 目前5个Boss不输出
                    if (s.IsBoss) continue;

                    rowNo = startAt + wikiaCounter;
                    IRow row = (sheet.GetRow(rowNo) == null) ? sheet.CreateRow(rowNo) : sheet.GetRow(rowNo);
                    ICell cellId = row.CreateCell(0);
                    cellId.SetCellValue(string.Format("No.{0:000}", s.Id));
                    ICell cellEnName = row.CreateCell(1);
                    cellEnName.SetCellValue(s.EnglishName);
                    ICell cellJpName = row.CreateCell(2);
                    cellJpName.SetCellValue(s.JapaneseName);
                    nameCache[s.JapaneseName] = rowNo;
                    wikiaCounter++;
                }

                rowNo = startAt;
                foreach (var s in appmedia)
                {
                    IRow row = (sheet.GetRow(rowNo) == null) ? sheet.CreateRow(rowNo) : sheet.GetRow(rowNo);
                    ICell cellJpName = row.CreateCell(5);
                    cellJpName.SetCellValue(s.JapaneseName);
                    ICell cellAppMediaId = row.CreateCell(6);
                    cellAppMediaId.SetCellValue(s.AppMediaId);

                    if (nameCache.ContainsKey(s.JapaneseName))
                    {
                        int wikiaRowNo = nameCache[s.JapaneseName];
                        IRow wikiaRow = sheet.GetRow(wikiaRowNo);
                        ICell cellMappingId = wikiaRow.CreateCell(3);
                        cellMappingId.SetCellValue(s.AppMediaId);
                        // ICell cellId = row.CreateCell(7);
                        // cellId.SetCellValue(wikiaRow.CreateCell(0).StringCellValue);
                    }
                    else
                    {
                        ICellStyle style = workbook.CreateCellStyle();
                        IFont font = workbook.CreateFont();
                        font.Color = HSSFColor.Red.Index;
                        style.SetFont(font);
                        cellJpName.CellStyle = style;
                    }

                    rowNo++;
                }

                rowNo = startAt + ((wikiaCounter > appmedia.Count) ? wikiaCounter : appmedia.Count) + 1;
            }

            Stream stream = new FileStream(@"D:\temp\servants.xlsx", FileMode.Create);
            workbook.Write(stream);
        }

        public static void ExportServantNames(List<ServantInfo> siList)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var si in siList)
            {
                sb.AppendLine(string.Format("{0}\t{1}\t{2}\t{3}", si.Id, si.JapaneseName, si.EnglishName, si.ChineseName));
            }
            File.WriteAllText(@"D:\temp\fgowiki_names.csv", sb.ToString());
        }
    }
}
